/**
 * Created by zhouli on 18/2/7
 * Email li.zhou@huilianyi.com
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import {
  Button, Badge,
  Tooltip, Icon, Popover,
  Dropdown, Menu,
  Modal, Upload, message, Radio
} from 'antd';
const RadioGroup = Radio.Group;
import LPService from 'containers/enterprise-manage/legal-person/legal-person.service';
import SearchArea from 'components/search-area.js';
import menuRoute from 'routes/menuRoute';
import ExportModal from 'components/template/export-modal/export-modal';
import ImportErrInfo from 'components/template/import-err-info';
import FileSaver from 'file-saver';
import ResizeTable from 'components/resize-table'
class LegalPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showImportPersonModel: false,
      progressImportErrInfo: 1,
      showImportErrInfo: false,
      transactionOID: null,
      errorsList: [
        {
          line: "",
          msg: ""
        },
      ],

      fileList: [],
      fileUploading: false,//文件是否正在上传
      downLoadTempList: [
        {
          type: 1,
          downloading: false,
          name: messages('enterprise-manage.key89'/*法人信息导入模板*/)
        },
      ],

      loading: true,
      data: [],
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
      },
      //搜索关键字
      params: {
        "keyword": ""
      },
      searchForm: [
        {
          type: 'input',
          key: 'keyword',    //必填，唯一，每行的标识
          id: 'keyword',
          label: messages('enterprise-manage.key90'/*法人实体名称*/),
        }
      ],
      //老集团表格
      columns: [
        {
          title: messages('enterprise-manage.key91'/*序号*/),
          dataIndex: 'index',
          width: 48
        },
        {
          title: messages('enterprise-manage.key90'/*法人实体名称*/),
          key: "companyName",
          dataIndex: 'companyName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text} overlayStyle={{maxWidth: 500}}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('enterprise-manage.key92'/*员工数量*/),//"员工数量",
          key: "userAmount",
          dataIndex: 'userAmount',
        },
        {
          title: messages('enterprise-manage.key93'/*状态*/),
          dataIndex: 'enable',
          width: '15%',
          render: enable => <Badge status={enable ? 'success' : 'error'}
                                   text={enable ? messages("common.enabled") : messages("common.disabled")}/>
        },
        {
          title: messages("common.operation"),//"操作",
          dataIndex: "id",
          key: "id",
          width: '15%',
          render: (text, record) => (
            <span>
              <a onClick={(e) => this.editItemLegalPerson(e, record)} disabled={!this.props.tenantMode}>
                     {/*编辑*/}
                {messages("common.edit")}
              </a>
              &nbsp;&nbsp;&nbsp;
              <a onClick={(e) => this.handleRowClick(e, record)}>
                {/*详情*/}
                {messages("common.detail")}
              </a>
            </span>)
        }
      ],
      //新集团表格
      columnsNew: [
        {
          title: messages('enterprise-manage.key91'/*序号*/),
          dataIndex: 'index',
          width: '8%'
        },
        {
          title: messages('enterprise-manage.key90'/*法人实体名称*/),
          key: "companyName",
          dataIndex: 'companyName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text} overlayStyle={{maxWidth: 500}}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('enterprise-manage.key93'/*状态*/),
          dataIndex: 'enable',
          width: '15%',
          render: enable => <Badge status={enable ? 'success' : 'error'}
                                   text={enable ? messages("common.enabled") : messages("common.disabled")}/>
        },
        {
          title: messages("common.operation"),//"操作",
          dataIndex: "id",
          key: "id",
          width: '15%',
          render: (text, record) => (
            <span>
              <a onClick={(e) => this.editItemLegalPerson(e, record)} disabled={!this.props.tenantMode}>
                {/*编辑*/}
                {messages("common.edit")}
              </a>
              &nbsp;&nbsp;&nbsp;
               <a onClick={(e) => this.handleRowClick(e, record)}>
                {/*详情*/}
                 {messages("common.detail")}
              </a>
            </span>)
        }
      ],
      visible: false,
      confirmLoading: false,
      scope: "ALL",
      id: "",//设置员工可见范围时需要用的ID
    }
  }

  componentWillMount(){
    this.getScope();
  }

  componentDidMount() {
    //记住页码
    let _pagination = this.getBeforePage();
    let pagination = this.state.pagination;
    pagination.page = _pagination.page;
    pagination.current = _pagination.page + 1;
    this.setState({
      pagination,
    }, () => {
      this.clearBeforePage();
      this.getLegalPersonList();
    })
  }

  //获取法人实体表格
  getLegalPersonList = () => {
    const { pagination, params } = this.state;
    this.setState({
      loading: true,
    });
    let item = {
      "keyword": params.keyword,
      "page": pagination.page,
      "size": pagination.pageSize,
    };
    LPService.getLegalList(item)
      .then((response) => {
        //加上序号
        response.data.map((item, index) => {
          item.index = pagination.page * pagination.pageSize + index + 1;
          item.key = item.index;
        });
        this.setState({
          loading: false,
          data: response.data,
          pagination: {
            page: pagination.page,
            pageSize: pagination.pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            total: Number(response.headers['x-total-count']),
          }
        })
      })
  };

  //点击搜搜索
  handleSearch = (values) => {
    this.setState({
      params: values,
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
      },
    }, () => {
      this.getLegalPersonList()
    })
  };

  //点击情况搜索
  clearSearchHandle = (values) => {
    let params = {
      keyword: ""
    };
    this.setState({
      params
    }, () => {
      this.getLegalPersonList()
    })
  };

  //新增法人实体
  handleCreateLP = () => {
    this.context.router.push(menuRoute.getMenuItemByAttr('legal-person', 'key').children.newLegalPerson.url);
  };

  //编辑法人实体
  editItemLegalPerson = (e, record) => {
    this.setBeforePage(this.state.pagination);
    e.stopPropagation();
    let _detailUrl = menuRoute.getMenuItemByAttr('legal-person', 'key').children.editLegalPerson.url;
    let detailUrl = _detailUrl.replace(':legalPersonOID', record.companyReceiptedOID);
    detailUrl = detailUrl.replace(':legalPersonID', record.id);
    this.context.router.push(detailUrl);
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getLegalPersonList();
    })
  };

  //点击行，进入该行详情页面
  //为了适应新老集团，这里传两个参数
  handleRowClick = (e,record) => {
    this.setBeforePage(this.state.pagination);
    let _detailUrl = menuRoute.getMenuItemByAttr('legal-person', 'key').children.legalPersonDetail.url;
    let detailUrl = _detailUrl.replace(':legalPersonOID', record.companyReceiptedOID);
    detailUrl = detailUrl.replace(':legalPersonID', record.id);
    this.context.router.push(detailUrl);
  };

  renderCreateBtn = () => {
    const menu = (
      <Menu>
        <Menu.Item key={1}>
          <span onClick={this.props.tenantMode && this.personImport}> {messages('enterprise-manage.key94'/*批量导入法人实体*/)}
          </span>
        </Menu.Item>
      </Menu>
    );
    return (
      <div className="table-header-buttons">
        <Dropdown.Button overlay={menu}
                         type="primary"
                         disabled={!this.props.tenantMode}
                         onClick={this.handleCreateLP}>
          {/*新增法人实体*/}
          {messages('enterprise-manage.key95'/*新增法人实体*/)}
        </Dropdown.Button>
        <Tooltip
          title={<div>
            <p>
              {messages('enterprise-manage.key96'/*1.法人实体名称是员工在法律上归属的公司注册名称,在应用开票平台开具增值税发票时,作为选择开票费用集合的单位*/)}
              {/*1.法人实体名称是员工在法律上归属的公司注册名称,*/}
              {/*在应用开票平台开具增值税发票时,作为选择开票费用集合的单位*/}
            </p>
            <p>
              {messages('enterprise-manage.key97'/*2.法人实体详细信息是员工个人开具增值税发票的必要信息,用户可在APP我的-开票信息中查看*/)}
              {/*2.法人实体详细信息是员工个人开具增值税发票的必要信息,*/}
              {/*用户可在APP我的-开票信息中查看*/}
            </p>
          </div>}>
          <span><Icon type="info-circle-o"/></span>
        </Tooltip>
       <div style={{display:"inline-block",margin:"0 10px 0 15px"}}>
         <ExportModal
           codeCheck={true}
           type={"btn"}
           exportTitle={messages('enterprise-manage.key334')/*导出法人实体*/}
           exportType="LEGAL_ENTITY"
           exportCondition={{"keyword": this.state.params.keyword}}
           exportCommand={"legal_entity"}/>
       </div>
        <div style={{display:"inline-block"}}><a onClick={this.clickSetScope}>{messages('enterprise-manage.key342')/*设置员工可见开票范围*/}</a></div>
      </div>
    )
  };

  //渲染下载模板
  renderDownTemp = (list) => {
    return list.map((data) => {
      return (
        <div style={{marginBottom: 10}} key={data.type}>
          <Button
            className='default-color-font'
            style={{border: 'none'}}
            size={'small'}
            icon="download"
            loading={data.downloading}
            onClick={() => {this.downloadTemplateByType(data.type)}}>
            {data.name}
          </Button>
        </div>
      )

    })
  };

  //下载模板
  downloadTemplateByType = (type) => {
    const { downLoadTempList } = this.state;
    downLoadTempList.map(item => {
      if(item.type === type){
        item.downloading = true
      }
    });
    this.setState({
      downLoadTempList,
    });
    switch (type) {
      case 1: {
        this.downloadLegalentitysTemplate(type);
        break;
      }
    }
  };

  // 下载法人信息
  downloadLegalentitysTemplate = (type) => {
    const { downLoadTempList } = this.state;
    LPService.downloadLegalentitysTemplate()
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = messages('enterprise-manage.key89'/*法人信息导入模板*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
        downLoadTempList.map(item => {
          if(item.type === type){
            item.downloading = false
          }
        });
        this.setState({
          downLoadTempList,
        });
      })
      .catch((err) => {
        downLoadTempList.map(item => {
          if(item.type === type){
            item.downloading = false
          }
        });
        this.setState({
          downLoadTempList,
        });
      })
  };

  clickSetScope = () => {
    this.setState({
      visible: true,
    });
  };


  onModalCancel = () => {
    this.setState({
      visible: false,
    });
    this.getScope();
  };

  getScope = () => {
    this.setState({
      loading: true,
    });
    LPService.getScope().then(res => {
      this.setState({
        loading: false,
        scope: res.data.scope,
        id: res.data.id,
      });
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  handleSetScope = () => {
    const { scope, id } = this.state;
    this.setState({
      confirmLoading: true,
    });
    let params = { id: id, scope: scope };
    LPService.setScope(params).then(res => {
      this.setState({
        confirmLoading: false,
        visible: false,
      });
    }).catch(err => {
      this.setState({
        confirmLoading: false,
      });
    })
  };

  //处理创建类型
  handleScopeType = (e) => {
    this.setState({
      scope: e.target.value,
    })
  };

  render() {
    const props = {
      onRemove: (file) => {
        this.setState(({fileList}) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        //只上传一个
        this.setState(({fileList}) => ({
          fileList: [file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };
    const {confirmLoading, searchForm, pagination, loading, data, columns, columnsNew, showImportPersonModel,
      downLoadTempList, fileUploading, fileList, progressImportErrInfo, errorsList, showImportErrInfo, visible, scope} = this.state;
    const verticalRadio = {
      display: "block",
      marginBottom: 15,
      fontWeight: 500,
    };
    return (
      <div className="legal-person-wrap">
        <SearchArea searchForm={searchForm}
                    clearHandle={this.clearSearchHandle}
                    submitHandle={this.handleSearch}/>

        <div className="table-header">
          <div className="table-header-title">
            {/*共搜索到*条数据*/}
            {messages('common.total',
              {total: `${pagination.total}`})}
          </div>
          {this.renderCreateBtn()}
        </div>

        {/*新集团是显示公司*/}
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={this.props.isOldCompany ? columns : columnsNew}
          pagination={pagination}
          size="middle"
          bordered
          onChange={this.onChangePager}/>
        <Modal
          closable
          width={800}
          className="pm-import-person-modal"
          title={messages('enterprise-manage.key35'/*导入*/)}//导入
          visible={showImportPersonModel}
          footer={null}
          onCancel={this.cancelImportPerson}
          destroyOnClose={true}>
          <div className="import-person-modal-wrap">
            <div className="f-left import-person-modal-left">
              <p className="import-person-left-tips">
                <h4>{messages('enterprise-manage.key36'/*创建模板*/)}</h4>
              </p>
              {
                this.renderDownTemp(downLoadTempList)
              }
              <div className="download-list-item-a-wrap">
                <a className="download-list-item-a"
                   href="http://helioscloud-uat-static.oss-cn-shanghai.aliyuncs.com/bank_info.xlsx"
                >
                  {messages('enterprise-manage.key37'/*银行基础数据（录入银行信息时请根据银行数据录入，该文件无须上传）*/)}
                </a>
              </div>
              <div>
                <div>{messages('enterprise-manage.key38'/*1.点击下载模板*/)}</div>
                <div>{messages('enterprise-manage.key39'/*2.严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}</div>
                <div>{messages('enterprise-manage.key40'/*3.关闭Excel文件后，方可进行数据导入*/)}</div>
              </div>
            </div>
            <div className="f-right import-person-modal-right">
              <div className="import-person-right-tips"> {messages('enterprise-manage.key41'/*上传模板*/)}
              </div>
              <div className="upload-file-wrap">
                <Upload {...props}>
                  <Button>
                    <Icon type="upload"/>
                    {messages('enterprise-manage.key42'/*选择一个文件*/)}
                  </Button>
                </Upload>
                <Button
                  className="upload-file-start"
                  type="primary"
                  onClick={this.handleFileUpload}
                  disabled={fileList.length === 0}
                  loading={fileUploading}>
                  {/*?上传中:开始上传*/}
                  {fileUploading ? messages('enterprise-manage.key43'/*上传中*/) : messages('enterprise-manage.key44'/*开始上传*/)}
                </Button>

              </div>
            </div>
            <div className="clear"/>
          </div>
        </Modal>
        <ImportErrInfo
          progress={progressImportErrInfo}
          cancel={this.hideImportErrInfo}
          exportErrInfo={this.exportFailedLog}
          title={messages('enterprise-manage.key98'/*法人实体导入错误*/)}
          errorsList={errorsList}
          visible={showImportErrInfo}/>
        <Modal visible={visible}
               title={messages('enterprise-manage.key342')/*设置员工可见开票范围*/}
               confirmLoading={confirmLoading}
               destroyOnClose={true}
               onOk={this.handleSetScope}
               onCancel={this.onModalCancel}>
                <div style={{marginLeft: 30}}>
                  <RadioGroup onChange={this.handleScopeType} value={scope}>
                    <Radio value={"ALL"}
                           style={verticalRadio}> {messages('enterprise-manage.key343')/*可见全部*/}
                    </Radio>
                    <Radio value={"SET_OF_BOOKS"}
                           style={verticalRadio}> {messages('enterprise-manage.key344')/*可见员工所在账套*/}
                    </Radio>
                    <Radio value={"LEGAL_ENTITY"}
                           style={verticalRadio}> {messages('enterprise-manage.key345')/*可见员工所在法人*/}
                    </Radio>
                  </RadioGroup>
                </div>
        </Modal>
      </div>
    )
  }


  //导入
  personImport = () => {
    this.setState({
      showImportPersonModel: true
    })
  };
  cancelImportPerson = () => {
    this.setState({
      showImportPersonModel: false
    })
  };

  handleFileUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();

    formData.append('file', fileList[0]);
    this.setState({
      uploading: true,
      fileUploading: true,
    });

    LPService.importCompanyOrBank(formData)
      .then((res) => {
        this.setState({
          fileList: [],
          uploading: false,
          fileUploading: false,
          showImportPersonModel: false,
          transactionOID: res.data.transactionOID
        }, () => {
          this.showImportErrInfo();
          this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
        });
      })
      .catch((res) => {
        this.setState({
          uploading: false,
          fileUploading: false,
        });
      })
  };

  showTransactionLogDialog = (transactionOID) => {
    LPService.getBatchTransactionLogNew(transactionOID)
      .then((res) => {
        let data = res.data;
        if (data.totalEntities === 0) {
          this.hideImportErrInfo();
          return;
        } else {
          let errors = data.errors;
          let errorsList = this.getErrorDataByerrors(errors);
          let progressImportErrInfo = this.getProgressByData(data);
          this.setState({
            progressImportErrInfo,
            errorsList
          });
          if ((data.successEntities + data.failureEntities) != data.totalEntities) {
            let gapTime = 500;
            setTimeout(() => {
              //请求频率涉及到一个算法
              this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
            },gapTime)
          }else {
            this.getLegalPersonList();
            if(this.state.errorsList.length === 0 && this.state.progressImportErrInfo === 100){
              message.success(messages("common.operate.success"));
              this.hideImportErrInfo();
            }
          }
        }
      })
  };

  //获取百分进度
  getProgressByData = (data) => {
    return Math.round((data.failureEntities + data.successEntities) * 100 / data.totalEntities);
  };

  //通过错误信息，解析成表格
  getErrorDataByerrors = (errs) => {
    let data = [];
    for (let key in errs) {
      let row = {};
      row.line = errs[key];
      if (row.line.length > 1) {
        let _line = [];
        for (let i = 0; i < row.line.length; i++) {
          _line.push(row.line[i]);
          if (i < row.line.length - 1) {
            _line.push(",");
          }
        }
        row.line = _line;
      }
      row.msg = key;
      data.push(row);
    }
    return data;
  };

  //法人实体导入错误
  exportFailedLog = () => {
    LPService.exportFailedLog(this.state.transactionOID)
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        // 法人实体错误信息
        let name = messages('enterprise-manage.key98'/*法人实体导入错误*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
      .catch((res) => {
      })
  };

  //人员导入的错误信息-start
  showImportErrInfo = () => {
    this.setState({
      showImportErrInfo: true
    })
  };

  hideImportErrInfo = () => {
    this.setState({
      showImportErrInfo: false
    })
  }

}

LegalPerson.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    isOldCompany: state.login.isOldCompany,
    tenantMode: state.main.tenantMode,
  }
}

LegalPerson.propTypes = {};

export default connect(mapStateToProps)(LegalPerson);



